package day18.pack4;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import day13.pack2.Penguin;
import day8.pack2.Car;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws Exception {
        Penguin penguin = new Penguin();
        penguin.setNickname("马化腾");
        penguin.setGender("男");

        Car car = new Car();
        car.setNo("赣M12345");
        car.setType("轿车");
        car.setBrand("BMW");
        car.setColor("白色");
        car.setMileage(100000);

        System.out.println(toJson(car));
        System.out.println(toJson(penguin));
    }

    public static String toJson(Object obj) throws InvocationTargetException, IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Method[] methods = clazz.getMethods();
        StringBuilder json = new StringBuilder("{");
        for (Method method : methods) {
            if(!method.getName().startsWith("get") ||
                    method.getName().equals("getClass")) continue;
            // getNickname
            String key = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4).toLowerCase();
            Object value = method.invoke(obj);
            json.append("\"");
            json.append(key);
            json.append("\"");
            json.append(":");
            if(value instanceof String) {
                json.append("\"");
                json.append(value);
                json.append("\"");
            } else {
                json.append(value);
            }
            json.append(",");
        }
        // 删除最后一个逗号
        json.deleteCharAt(json.length() - 1);
        json.append("}");
        return json.toString();
    }

}
